//
//  NetworkTools + OAuth.swift
//  
//
//  Created by 王璐 on 2017/4/26.
//
//

import Foundation

extension NetworkTools {
    
//    func oauthUrl() -> NSURL{
    //计算型属性 不能接受参数,语义更好
    var oauthUrl:NSURL{
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redlrectUrl)"
        
        return NSURL(string: urlString)!
    }
    
    /// 加载accessToken
    ///
    /// - parameter code:     code 授权码
    /// - parameter finished: 完成回调(字典)
    func loadAccessToken(code:String,finished:@escaping ([String:AnyObject]?)->()){
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        let parms = [
            "client_id":appKey,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redlrectUrl]

        request(method: .POST, urlString: urlStr, parameters: parms as [String : AnyObject]?){result in
            guard let result = result,
                let access_token = result["access_token"] as? String,
                let uid = result["uid"] else{
                    print("数据格式不正确")
                    finished(nil)
                    return
            }
            
            //加载用户数据
            self.loadUser(access_token: access_token, uid: uid as! String, finished: { (userDict) in
               // print(userDict ?? 0)
                
                //合并字典
                //1.判断用户字典是否有值
                guard var userDict = userDict else{
                    print("用户数据加载错误")
                    finished(nil)
                    return
                }
                //2.合并
                for (k,v) in result{
                    userDict[k] = v
                }
                
                //3.完成回调
                finished(userDict)
            })
            
        }
    }
    
}
